#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;

vector<vector<int>> threeSum(vector<int>& nums)
{
    sort(nums.begin(), nums.end());
    int i = 0;
    vector<int> v;
    vector<vector<int>> vv;
    while(i<nums.size())
    {
        if (nums[i] > 0)
        {
            break;
        }
        int left = i + 1;
        int right = nums.size() - 1;
        while (left < right)
        {
            if (nums[left] + nums[right] > -nums[i])
            {
                right--;
            }
            else if (nums[left] + nums[right] < -nums[i])
            {
                left++;
            }
            else
            {
                //nums[left] + nums[right] = -nums[i]
                while (left < right && nums[left] == nums[left + 1])
                {
                    left++;
                }
                while (left < right && nums[right] == nums[right- 1])
                {
                    right--;
                }
                v.push_back(nums[left]);
                v.push_back(nums[right]);
                v.push_back(nums[i]);
                left++;
                right--;
                vv.push_back(v);
                v.clear();
            }
        }
        i++;
        while (i < nums.size() && nums[i] == nums[i - 1])
        {
            i++;
        }
    }
    return vv;
}


int main()
{
    vector<int> v = { -1,0,1,2,-1,-4};
    vector<vector<int>> ret = threeSum(v);
    vector<int>::iterator it;
    vector<vector<int>>::iterator iter;
    vector<int> vec_tmp;
    for (iter = ret.begin(); iter != ret.end(); iter++)
    {
        vec_tmp = *iter;
        for (it = vec_tmp.begin(); it != vec_tmp.end(); it++)
            cout << *it << " ";
        cout << endl;
    }
    return 0;
}